//
//  UIButtonExtension.swift
//  HHSwift
//
//  Created by 华宏 on 2019/10/14.
//  Copyright © 2019 huahong. All rights reserved.
//

import Foundation

enum ButtonEdgeInsetsStyle {
    case top     //image在上
    case left    //image在左
    case bottom  //image在下
    case right   //image在右
}
extension UIButton{
     
    func layoutEdgeInsetsWithStyle/*<T:FloatingPoint>*/(style:ButtonEdgeInsetsStyle,space:CGFloat) {
      
        self.layoutIfNeeded()
        
        
    //        let currentTitle:NSString = (button.currentTitle ?? "") as NSString
    //        var titleLabelWidth = currentTitle.boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: self.bounds.size.height), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font:button.titleLabel?.font ?? UIFont.systemFont(ofSize: 14)], context: nil).size.width
            

    //        let titleLabelWidth = button.titleLabel?.intrinsicContentSize.width ?? 0
        let titleWidth = self.titleLabel?.bounds.size.width ?? 0
        let titleHeight = self.titleLabel?.bounds.size.height ?? 0

        let imageWidth = self.imageView?.bounds.size.width ?? 0
        let imageHeight = self.imageView?.bounds.size.height ?? 0
            

        var imageInsets = UIEdgeInsets.zero
        var titleInsets = UIEdgeInsets.zero

        switch style {
        case .top:
           imageInsets = UIEdgeInsets(top: -(imageHeight+space)/2.0, left: titleWidth*0.5, bottom: (imageHeight+space)/2.0, right: -titleWidth*0.5);
           titleInsets = UIEdgeInsets(top: (titleHeight+space)/2.0, left: -imageWidth*0.5, bottom: -(titleHeight+space)/2.0, right: imageWidth*0.5);
            
        case .left:
            imageInsets = UIEdgeInsets(top: 0, left: -space*0.5, bottom: 0, right: space*0.5);
            titleInsets = UIEdgeInsets(top: 0, left: space*0.5, bottom: 0, right: -space*0.5);
            
        case .bottom:
            imageInsets = UIEdgeInsets(top: (imageHeight+space)/2.0, left: titleWidth*0.5, bottom: -(imageHeight+space)/2.0, right: -titleWidth*0.5);
            titleInsets = UIEdgeInsets(top: -(titleHeight+space/2.0), left: -imageWidth*0.5, bottom: (titleHeight+space/2.0),right: imageWidth*0.5);
            
        case .right:
            imageInsets = UIEdgeInsets(top: 0, left: (titleWidth+space*0.5), bottom: 0, right: -(titleWidth+space*0.5));
            titleInsets = UIEdgeInsets(top: 0, left: -(imageWidth+space*0.5), bottom: 0, right: (imageWidth+space*0.5));
        
        }
        
        
        
       self.titleEdgeInsets = titleInsets
       self.imageEdgeInsets = imageInsets
        
            
        }
}
